package com.skyz.base.mvp;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleEventObserver;
import androidx.lifecycle.LifecycleOwner;

import java.lang.ref.SoftReference;

public abstract class BasePresenter<M extends IModel, V extends IView> implements LifecycleEventObserver {

    protected final String TAG = getClass().getSimpleName();

    private M mMvpModel;
    private SoftReference<V> mViewSoftReference;

    private Lifecycle mLifecycle;

    public BasePresenter(V view, Lifecycle lifecycle) {
        if (view == null) {
            Log.w(TAG, "You can not input a null view!");
            return;
        }
        if (lifecycle == null) {
            Log.w(TAG, "You can not input a null lifecycle!");
            return;
        }
        this.mLifecycle = lifecycle;
        mLifecycle.addObserver(this);
        attachView(view);
    }

    private void attachView(V view) {
        mViewSoftReference = new SoftReference<>(view);
        mMvpModel = initMvpModel();
        if (mMvpModel == null) {
            Log.w(TAG, "You may forget to init mvp model!");
            return;
        }
        Log.i(TAG, "attach view " + mViewSoftReference.get().getClass().getName());
    }

    private void detachView() {
        Log.i(TAG, "detach view " + mViewSoftReference.get().getClass().getName());
        mViewSoftReference.clear();
    }

    @Override
    public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) {
        if (event == Lifecycle.Event.ON_DESTROY) {
            detachView();
            mLifecycle.removeObserver(this);
        }
    }

    protected abstract M initMvpModel();


    protected V getMvpView() {
        return mViewSoftReference.get();
    }

    protected M getMvpModel() {
        return mMvpModel;
    }


}
